package com.gitee.magic.framework.base.constant;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.core.utils.CheckUtils;
import com.gitee.magic.core.utils.StringUtils;
import com.gitee.magic.framework.head.constants.BaseCode;

/**
 * @author start
 */
public class Message {

	private Integer code;
	private String message;

	public Message(Integer code, String message) {
		this.code = code;
		this.message = message;
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	public String getFullMessage() {
		return getCode()+"-"+getMessage();
	}
	
	public static Message parse(String message){
		if(StringUtils.isEmpty(message)){
			return parse(BaseCode.CODE_1000);
		}
		int code=0;
		String splitStr="-";
		if(message.indexOf(splitStr)!=-1) {
			String codeStr=message.substring(0,message.indexOf("-"));
			if(CheckUtils.isInteger(codeStr)) {
				code=Integer.parseInt(codeStr);
				message=message.substring(message.indexOf("-")+1);
			}
		}
		return new Message(code,message);
	}
	
	public static Message parse(String v,Class<? extends BaseCode> code) {
		String s="-";
		if(v.indexOf(s)==-1) {
			Field[] fields=code.getFields();
			for(Field f:fields) {
				Object value=null;
				try {
					value=f.get(null);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					throw new ApplicationException(e);
				}
				if(value!=null) {
					String vv=String.valueOf(value);
					if(v.equals(vv)) {
						String regex="[^0-9]";
						Pattern compile=Pattern.compile(regex);
						Matcher matcher=compile.matcher(f.getName());
						String c=matcher.replaceAll("").toString();
						return Message.parse(c+"-"+v);
					}
				}
			}
		}
		return Message.parse(v);
	}
	
	public static void main(String[] args) {
		String m=BaseCode.CODE_200;
		Message m1=Message.parse(m,BaseCode.class);
		System.out.println(m1.getCode());
		System.out.println(m1.getMessage());
	}

}
